#include "net.h"
#include "staff_system.h"
int IPV4_init(int mode, int rank, int argc, const char *argv[])
{
	//判错
	if(argc<3){
		fprintf(stderr, "Usage: %s <IP> <PORT>\n", argv[0]);
		return 0;
	}

	//socket,创建套接字
	int sockfd = socket(AF_INET, mode, 0);
	if(sockfd <0){
		err_log("socket err.");	
	}else{
		printf("socket ok.\n");
	}
	//填充结构体
	struct sockaddr_in serveraddr;
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
	socklen_t addrlen = sizeof(struct sockaddr);

	//允许地址与端口复用
	int optval = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
	//服务器模式
	if(rank == SERVER){
		//绑定
		if(bind(sockfd, (struct sockaddr *)&serveraddr, addrlen)<0){
			err_log("bind err.");	
		}else{
			printf("bind ok.\n");
		}
		if(mode == SOCK_STREAM){
			//listen,监听
			if(listen(sockfd, 2)<0){
				err_log("listen err.");	
			}else{
				printf("listen ok.\n");
			}
		}
	}
	//客户端模式
	if(rank == CLIENT){
		if(connect(sockfd, (struct sockaddr *)&serveraddr, addrlen)<0){
			err_log("connect err.");	
		}else{
			printf("connect ok.\n");
		}
	}

	return sockfd;
}


